import storage from '@/utils/storage'
import constant from '@/utils/constant'
import {
  getRouters
} from '@/api/login'

const workbench = {
  state: {
    workbench: storage.get(constant.workbench)||[],
    routers: [],
  },

  mutations: {
    SET_WORKBENCH: (state, workbench) => {
      state.workbench = workbench
      storage.set(constant.workbench, workbench)
    },
    SET_ROUTERS: (state, routers) => {
      state.routers = routers
    },
  },

  actions: {
    // 获取全部菜单
    GetRouters({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getRouters().then(res => {
          let data = res.data.filter(x => x.children ?? null)
            .map(x => {
              return {
                title: x.meta.title,
                children: [].concat.apply([],x.children.map(x=>x.children?x.children:x))
              };
            })
            .reverse();
          data.push({
            title: '其它',
            children: res.data.filter(x => !(x.children ?? null))
          });
          data.map(x=>{
            x.children = x.children.map(x=>({
              icon: x.meta.icon,
              title: x.meta.title,
              link: x.meta.link,
              path: '/pageswork/'+x.component,
            }));
            return x
          })
          commit('SET_ROUTERS',data);
          resolve(data)
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      })
    }
  }
}

export default workbench